<template>
  <div class="page-common-layout custom-tablePage-container">
    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <a-input
            v-model="condition.contractName"
            placeholder="请输入合同名称"
            style="width:300px"
          ></a-input>
          <a-select
            placeholder="请选择合同类型"
            v-model="condition.contractType"
            showSearch
            :filter-option="filterOption"
            :loading="contractTypeLoading"
            @change="search()"
          >
            <a-select-option
              :value="item.dicItemCode"
              v-for="item in contractTypeSource"
              :key="item.dicItemCode"
            >
              {{ item.dicItemName }}
            </a-select-option>
          </a-select>
          <a-range-picker
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            :placeholder="['归档开始日期', '归档结束日期']"
            v-model="condition.date"
            :show-time="false"
          />
        </template>
        <template slot="operate">
          <a-button class="cu-btn-primary" icon="search" @click="search()">
            查询
          </a-button>
          <a-button class="cu-btn-filter" icon="reload" @click="reset()">
            重置
          </a-button>
        </template>
      </ScreenConditions>
    </div>
    <div class="table-body-container">
      <div class="table-operate">
        <!-- <a-button
          @click="handleAddModal({}, 1)"
          class="cu-btn-primary margin-bottom-xs"
          icon="plus"
          v-action:htbab_add
        >
          新增
        </a-button> -->
      </div>
      <div class="table-main">
        <vxe-table
          ref="xTable"
          height="99%"
          align="center"
          show-overflow
          show-header-overflow
          border="inner"
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="loading"
        >
          <vxe-column type="seq" width="80" title="序号"></vxe-column>
          <vxe-column field="contractName" title="合同名称"> </vxe-column>
          <vxe-column field="contractTypeDesc" title="合同类型"> </vxe-column>
          <vxe-column field="otherFiles" title="合同文件">
            <template #default="{ row}">
              <div class="files-icon">
                <a-tooltip placement="top">
                  <template slot="title">
                    预览
                  </template>
                  <a-icon
                    type="eye"
                    class="preview-btn"
                    :class="[isEmptyObject(row.otherFiles) && 'disabled']"
                    @click="handelFileModal(row.otherFiles, '合同文件')"
                  />
                </a-tooltip>
                <a-tooltip placement="top" v-action:htbab_download>
                  <template slot="title">
                    {{ row.otherFiles["downloadStatus"] ? "下载中" : "下载" }}
                  </template>
                  <a-icon
                    v-if="row.otherFiles['downloadStatus']"
                    type="sync"
                    spin
                  />
                  <a-icon
                    v-else
                    type="download"
                    class="download-btn"
                    :class="[isEmptyObject(row.otherFiles) && 'disabled']"
                    @click="downloadFile(row.otherFiles, '合同文件')"
                  />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
          <vxe-column field="filingFormFiles" title="合同备案表">
            <template #default="{ row}">
              <div class="files-icon">
                <a-tooltip placement="top">
                  <template slot="title">
                    预览
                  </template>
                  <a-icon
                    type="eye"
                    class="preview-btn"
                    :class="[isEmptyObject(row.filingFormFiles) && 'disabled']"
                    @click="handelFileModal(row.filingFormFiles, '合同备案表')"
                  />
                </a-tooltip>
                <a-tooltip placement="top" v-action:htbab_download>
                  <template slot="title">
                    {{
                      row.filingFormFiles["downloadStatus"] ? "下载中" : "下载"
                    }}
                  </template>
                  <a-icon
                    v-if="row.filingFormFiles['downloadStatus']"
                    type="sync"
                    spin
                  />
                  <a-icon
                    v-else
                    type="download"
                    class="download-btn"
                    :class="[isEmptyObject(row.filingFormFiles) && 'disabled']"
                    @click="downloadFile(row.filingFormFiles, '合同备案表')"
                  />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
          <vxe-column field="modifyTime" title="归档时间"> </vxe-column>
          <vxe-column field="remark" title="其他备案信息"> </vxe-column>
          <vxe-column field="creator" title="提交人"> </vxe-column>
          <vxe-column field="createTime" title="提交时间"> </vxe-column>
          <!-- <vxe-column field="operate" width="100" title="操作" fixed="right">
            <template #default="{ row }">
              <div class="text-button-group">
                <a-tooltip placement="top">
                  <template slot="title">
                    查看
                  </template>
                  <a-icon type="file-search" @click="handleAddModal(row)" />
                </a-tooltip>
              </div>
            </template>
          </vxe-column> -->
        </vxe-table>
      </div>
      <div class="table-pager">
        <vxe-pager
          size="small"
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
          :page-sizes="[20, 50, 100, 500]"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              共<span>{{ pager.total }}</span
              >条
            </div>
          </template>
        </vxe-pager>
      </div>
    </div>
    <!-- 查看附件 -->
    <viewFileModal
      :visible.sync="viewFileModal.visible"
      :fileList="viewFileModal.fileList"
      :subtitle="viewFileModal.name"
    ></viewFileModal>
    <!-- 附件预览 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
    <!-- 详情 -->
    <detailModal
      :visible.sync="detailModal.visible"
      :row="detailModal.row"
    ></detailModal>
  </div>
</template>

<script>
//合同备案
import { _getUUID } from "@/utils/util.js";
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
//审批记录
import { getContractByProCode } from "@/api/cantonManage";
import { axios } from "@/utils/request";
import { getToken, downloadDfs } from "@/utils/TopVUI";
import { mapGetters } from "vuex";
import { getDicItemByCode } from "@/api/common.js";
//文件列表
import viewFileModal from "@/components/extendCustom/view-file-modal";
//单文件预览
import previewModal from "@/pages/document/minio/previewModal";
//详情
import detailModal from "./detailModal.vue";
export default {
  components: {
    ScreenConditions,
    viewFileModal,
    previewModal,
    detailModal,
  },
  data() {
    return {
      //合同名称
      contractLoading: false,
      contractSource: [],
      //合同类型
      contractTypeLoading: false,
      contractTypeSource: [],
      //查询条件
      condition: {
        //合同名称
        contractName: "",
        //合同类型
        contractType: undefined,
        //归档时间
        date: [],
      },
      //列表
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      //查看附件
      viewFileModal: {
        name: "",
        visible: false,
        fileList: [],
      },
      //单文件预览
      previewModal: {
        visible: false,
        loading: false,
      },
      //详情
      detailModal: {
        visible: false,
        row: {},
      },
    };
  },
  computed: {
    ...mapGetters(["configData", "userInfo"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  mounted() {
    this.getData();
  },
  methods: {
    //查询数据
    async getData() {
      await this.getTableData();
      //合同类型
      this.contractTypeSource = await this.getDicCodeData("contractType");
      await this.getContractData();
    },

    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    // 查看
    handleAddModal(row) {
      this.detailModal.row = row;
      this.detailModal.visible = true;
    },

    //是否是空对象
    isEmptyObject(obj = {}) {
      try {
        let data = JSON.parse(obj);
        if (data.length > 0) {
          return false;
        } else {
          return true;
        }
      } catch (error) {
        return true;
      }
    },

    //预览
    handelFileModal(files, name) {
      const filesList = this.analysisPath(files);
      let { url } = filesList?.[0] ?? {};
      if (filesList.length == 0) {
        return;
      }
      if (filesList.length == 1) {
        this.defaultViewFile(url);
      } else {
        this.viewFileModal.name = name;
        this.viewFileModal.fileList = filesList;
        this.viewFileModal.visible = true;
      }
    },

    //普通文件预览
    defaultViewFile(url) {
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },

    //下载
    downloadFile(files = "[]", name) {
      const filesList = this.analysisPath(files);
      let { url } = filesList?.[0] ?? {};
      if (filesList.length == 0) {
        return;
      }
      if (filesList.length == 1) {
        downloadDfs(url);
      } else {
        this.viewFileModal.name = name;
        this.viewFileModal.fileList = filesList;
        this.viewFileModal.visible = true;
      }
    },

    analysisPath(files = "[]") {
      let list = JSON.parse(files ?? "[]");
      return list;
    },

    //审批记录
    gotoApprovalRecord(record) {
      this.$refs.commentModal.getCommentList(record.uuid);
    },

    //查询合同
    getContractData() {
      this.contractLoading = true;
      return new Promise((resolve, reject) => {
        getContractByProCode()
          .then((res) => {
            this.contractSource = res ?? [];
            resolve();
          })
          .catch((_) => {
            this.contractSource = [];
            reject();
          })
          .finally((_) => {
            this.contractLoading = false;
          });
      });
    },

    //查询
    search() {
      this.pager.page = 1;
      this.getTableData();
    },

    //重置
    reset() {
      this.condition.contractName = undefined;
      this.condition.contractType = undefined;
      this.condition.date = [];
      this.search();
    },

    //查询列表数据
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      let { contractName = "", contractType = "", date } = this.condition;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/contractApprovalProcess/getFilingContractPageSet?pageNo=${page}&pageSize=${pageSize}`,
            {
              contractName,
              contractType,
              startTime: date?.[0] ?? "",
              endTime: date?.[1] ?? "",
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            this.tableData = data?.rows || [];
            this.pager.total = res?.totalCount || 0;
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.pager.total = 0;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },

    filterStateName(val) {
      switch (val) {
        case 0:
          return "待提交";
        case 1:
          return "审批中";
        case 2:
          return "审批通过";
        case 3:
          return "驳回";
        default:
          return "-";
      }
    },

    filterStateClass(val) {
      switch (val) {
        case 0:
          return "default";
        case 1:
          return "ing";
        case 2:
          return "lock";
        case 3:
          return "error";
        default:
          return "";
      }
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.file-button {
  position: absolute;
  right: 10px;
}

.state {
  &::before {
    position: relative;
    display: inline-block;
    content: "";
    width: 8px;
    height: 8px;
    background: #239b53;
    border-radius: 0px 0px 0px 0px;
    border-radius: 50%;
    margin-right: 10px;
  }
  &.default {
    &::before {
      background: #8c8c8c;
    }
  }
  &.ing {
    &::before {
      background: #f07f17;
    }
  }
  &.lock {
    &::before {
      background: #239b53;
    }
  }

  &.error {
    &::before {
      background: #ff3f4a;
    }
  }
}
</style>
